package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.framework.entity.Oplog;
import com.ldk.framework.service.IOplogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.RoadLine;
import com.ldk.framework.entity.ServiceConfig;
import com.ldk.framework.service.IRoadLineService;
import com.ldk.framework.service.IServiceConfigService;

@Controller
@RequestMapping("/roadline")
public class RoadLineController extends BaseController {
	/**
	 * 路由地址
	 */
	private final String route = "roadline";
	/**
	 * 模块名称
	 */
	private final String module = "路线";

	@Autowired
	private IRoadLineService roadLineService;
	@Autowired
	private IServiceConfigService serviceConfigService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		if (this.getRoleId(request) == 6) {
			setLinks(map, "", "", module+"管理", "/"+route+"/list", "", "");
		} else {
			setLinks(map, "", "", module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add");
		}

		map.addAttribute("route", route);
		map.addAttribute("module", module);

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/roadline/list_sj");
		} else {
			return new ModelAndView("/roadline/list");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<RoadLine> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									           @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									           @RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
									           HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		RoadLine query = new RoadLine();
		if(!StringUtils.isBlank(searchKey)){
			query.setSearchKey(searchKey);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		
		Page<RoadLine> result = roadLineService.selectPageList("", query, pageable);
		
		LigerUIGridResult<RoadLine> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map,HttpServletRequest request,
							HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		map.addAttribute("route", module);
		map.addAttribute("module", module);
		map.addAttribute("serviceList", getServiceConfigList());
		
		RoadLine model = new RoadLine();
		
		return new ModelAndView("/roadline/info","model",model);
	}
	
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable long id, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		RoadLine query = new RoadLine();
		query.setRoadId(id);
		
		RoadLine model = roadLineService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+id, "", "");
		setForm(map, "/"+route+"/update", null);
		map.addAttribute("route", module);
		map.addAttribute("module", module);
		map.addAttribute("serviceList", getServiceConfigList());
		
		return new ModelAndView("/roadline/info","model", model);
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") RoadLine model,
							   RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		try{
			if(model.getEnabled() == null){
				model.setEnabled(false);
			}
			model.setOperateTime(SystemUtil.getAllSeconds());
			model.setOperator(getAdminTrueName(request));

			//操作日志
			this.insertOplog(request,module,"","","添加:"+model.getRoadName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		    int row = roadLineService.insert("",model);
		    if(row > 0){
		    	rst.AddOk("添加"+module+"成功");
		    }
		    else{
		    	rst.AddError("添加"+module+"失败");
		    }
		}
		catch(Exception e){
			rst.AddError("添加"+module+"失败");
			logger.error(e.getMessage());
		}
		return new ModelAndView("redirect:/"+route+"/add");
	}
	
	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") RoadLine model,
			   				   RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response)
	{
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();

		redAttr.addAttribute("id", model.getRoadId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		try{
			if(model.getEnabled() == null){
				model.setEnabled(false);
			}
			model.setOperateTime(SystemUtil.getAllSeconds());
			model.setOperator(getAdminTrueName(request));

			//操作日志
			this.insertOplog(request,module,"","","修改:"+model.getRoadName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			int row = roadLineService.updateByKey("", model);
		    if(row > 0){
		    	rst.AddOk("修改"+module+"成功");
		    }
		    else{
		    	rst.AddError("修改"+module+"失败");
		    }
		}
		catch(Exception e){
			rst.AddError("修改"+module+"失败");
			logger.error(e.getMessage());
		}
		
		return new ModelAndView("redirect:/"+route+"/edit/{id}");
	}
	
	/**
	 * 浏览
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/view/{id}")
	public ModelAndView view(@PathVariable long id, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setViewMode(map, ViewMode.View);
		RoadLine query = new RoadLine();
		query.setRoadId(id);
		RoadLine model = roadLineService.selectByKey("", query);
		map.addAttribute("route", route);
		map.addAttribute("module", module);
		map.addAttribute("serviceList", getServiceConfigList());
		
		return new ModelAndView("/roadline/info","model", model);
	}
	
	@ResponseBody
	@RequestMapping("/remove/{id}")
	public ResponseResult remove(@PathVariable long id, HttpServletRequest request){
		
		ResponseResult rst = new ResponseResult();
		if(id < 1)
		{
			rst.AddError("删除"+module+"错误");
			return rst;
		}
		Boolean successed = false;
		try{
			RoadLine query = new RoadLine();
			query.setRoadId(id);

			RoadLine roadLine = roadLineService.selectByKey("", query);
			//操作日志
			this.insertOplog(request,module,"","","删除:"+roadLine.getRoadName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

			int row = roadLineService.deleteByKey("", query);
			successed = row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(successed){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}
		
		return rst;
	}
	/**
	 * 获取配置服务业务
	 * @return
	 */
	private List<ServiceConfig> getServiceConfigList(){
		ServiceConfig query = new ServiceConfig();
		query.setEnabled(true);
		
		return serviceConfigService.selectList("", query);
	}
}
